import socket
import pyaudio


UDP_IP = "0.0.0.0"  
UDP_PORT = 8888  

# 音频配置
CHUNK = 1024 
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100 
# 初始化pyaudio
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                output=True,
                frames_per_buffer=CHUNK)
# 创建UDP
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

print("Listening for audio data...")

try:
    while True:
        data, addr = sock.recvfrom(CHUNK)  # 接收数据
        # print(data)
        stream.write(data)  # 播放音频
except KeyboardInterrupt:
    print("Stopping...")
finally:
    stream.stop_stream()
    stream.close()
    p.terminate()
    sock.close()
